package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.bean.RecordBean;
import flc.ast.databinding.ActivityPicFormatBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.ToastUtil;

public class PicFormatActivity extends BaseAc<ActivityPicFormatBinding> {

    public static String imgPath;
    private String selFormat = "", newName = "";
    private Dialog myRenameDialog, myFormatTurnDialog;
    private TextView dialogFormatTurnTitle, dialogFormatTurnText, dialogFormatPro, dialogFormatTurnComp;
    private ProgressBar pbFormat;
    private EditText dialogRename;
    private Bitmap.CompressFormat format;
    private Bitmap bitmap;

    @Override
    protected int onCreate() {
        return R.layout.activity_pic_format;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event5Container);
        mDataBinding.ivPicFormatBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        Glide.with(mContext).load(imgPath).into(mDataBinding.ivPicFormatImg);
        bitmap = BitmapFactory.decodeFile(imgPath);
        mDataBinding.tvFormatPng.setOnClickListener(this);
        mDataBinding.tvFormatJpg.setOnClickListener(this);
        mDataBinding.tvFormatWebp.setOnClickListener(this);
        mDataBinding.tvPicFormatStart.setOnClickListener(this);
        mDataBinding.llFileName.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvFormatPng:
                clearFormat();
                mDataBinding.tvFormatPng.setBackgroundResource(R.drawable.kk2);
                format = Bitmap.CompressFormat.PNG;
                selFormat = ".png";
                break;
            case R.id.tvFormatJpg:
                clearFormat();
                mDataBinding.tvFormatJpg.setBackgroundResource(R.drawable.kk2);
                format = Bitmap.CompressFormat.JPEG;
                selFormat = ".jpg";
                break;
            case R.id.tvFormatWebp:
                clearFormat();
                mDataBinding.tvFormatWebp.setBackgroundResource(R.drawable.kk2);
                format = Bitmap.CompressFormat.WEBP;
                selFormat = ".webp";
                break;
            case R.id.llFileName:
                renameDialog();
                myRenameDialog.show();
                break;
            case R.id.ivDialogFormatRenameCancel:
                myRenameDialog.dismiss();
                break;
            case R.id.ivDialogFormatRenameConfirm:
                newName = dialogRename.getText().toString();
                mDataBinding.tvFileName.setText(newName);
                myRenameDialog.dismiss();
                break;
            case R.id.tvPicFormatStart:
                formatTurnDialog();
                startConv();
                break;
        }

    }

    private void startConv() {
        if (TextUtils.isEmpty(selFormat)) {
            ToastUtils.showShort(R.string.please_sel_format);
        } else if (TextUtils.isEmpty(newName)) {
            ToastUtils.showShort(R.string.please_input_name);
        } else {
            File file = ImageUtils.save2Album(bitmap, format);
            String path = file.getPath();
            RxUtil.create(new RxUtil.Callback<String>() {
                @Override
                public void doBackground(ObservableEmitter<String> emitter) {
                    String filePath = FileUtil.generateFilePath(Content.myTemp, selFormat);
                    FileUtils.copy(path, filePath);
                    emitter.onNext(filePath);
                }

                @Override
                public void accept(String savePath) {
                    //重命名
                    FileUtils.rename(savePath, newName + selFormat);
                    String newPath = PathUtils.getFilesPathExternalFirst() + Content.myTemp + "/" + newName + selFormat;
                    //保存到相册
                    file.delete();
                    saveRecord(newPath, 100, true);
                    FileP2pUtil.copyPrivateImgToPublic(mContext, newPath);
                    ToastUtils.showShort(getText(R.string.save_suc));
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            startActivity(HomeActivity.class);
                            finish();
                        }
                    }, 500);
                }
            });
        }
    }

    private void saveRecord(String imgPath, int progress, boolean isComp) {
        int index = selFormat.indexOf(".");
        String format = selFormat.substring(index + 1);
        List<RecordBean> listSave = new ArrayList<>();
        listSave.add(new RecordBean(imgPath, FileUtils.getFileName(imgPath), format, progress, isComp, false, 0));
        List<RecordBean> listSp = SPUtil.getObject(mContext, new TypeToken<List<RecordBean>>() {
        }.getType());
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            SPUtil.putObject(mContext, listSp, new TypeToken<List<RecordBean>>() {
            }.getType());
        } else {
            SPUtil.putObject(mContext, listSave, new TypeToken<List<RecordBean>>() {
            }.getType());
        }
    }

    @Override
    protected void initData() {
        String fileName = FileUtils.getFileName(imgPath);
        int index = fileName.indexOf(".");
        String startFormat = fileName.substring(index + 1, fileName.length());
        mDataBinding.tvFileName.setText(getString(R.string.please_input_name));
        mDataBinding.tvStartFormat.setText(getString(R.string.play_format_text2) + startFormat);
    }


    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_format_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogFormatRenameCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogFormatRenameConfirm);
        TextView dialogFormat = inflate.findViewById(R.id.tvDialogFormat);
        dialogRename = inflate.findViewById(R.id.etDialogFormatRename);
        String fileName = FileUtils.getFileName(imgPath);
        int index = fileName.indexOf(".");
        String startFormat = fileName.substring(index + 1, fileName.length());
        if (selFormat.isEmpty()) {
            dialogFormat.setText("." + startFormat);
        } else {
            dialogFormat.setText(selFormat);
        }
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    private void formatTurnDialog() {
        myFormatTurnDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_format_turn, null);
        myFormatTurnDialog.setContentView(inflate);
        myFormatTurnDialog.setCancelable(true);
        Window dialogWindow = myFormatTurnDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);

        dialogFormatTurnTitle = inflate.findViewById(R.id.tvDialogFormatTurnTitle);
        dialogFormatTurnText = inflate.findViewById(R.id.tvDialogFormatTurnText);
        dialogFormatPro = inflate.findViewById(R.id.tvDialogFormatPro);
        dialogFormatTurnComp = inflate.findViewById(R.id.tvDialogFormatTurnComp);
        pbFormat = inflate.findViewById(R.id.pbFormat);
        dialogFormatTurnComp.setOnClickListener(this);

    }

    private void clearFormat() {
        mDataBinding.tvFormatJpg.setBackgroundResource(R.drawable.shape_format);
        mDataBinding.tvFormatWebp.setBackgroundResource(R.drawable.shape_format);
        mDataBinding.tvFormatPng.setBackgroundResource(R.drawable.shape_format);
    }

}